package com.gjy.util.concurrent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveAction;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-06-17 11:25:02
 */
public class DbRecursiveAction extends RecursiveAction {

    private static final Logger log = LoggerFactory.getLogger(DbRecursiveAction.class);

    private static final Integer THRESHOLD = 1000;
    private final List<String> sqls;
    private final String url;
    private final String username;
    private final String password;

    public DbRecursiveAction(List<String> sqls, String url, String username, String password) {
        this.sqls = sqls;
        this.url = url;
        this.username = username;
        this.password = password;
    }

    @Override
    protected void compute() {
        if (sqls.size() < THRESHOLD) {
            log.info("执行SQL");
            executeBatch(sqls);
        } else {
            log.info("拆分SQL");
            List<List<String>> partition = averageAssign(sqls, 2);
            DbRecursiveAction db1 = new DbRecursiveAction(partition.get(0), url, username, password);
            DbRecursiveAction db2 = new DbRecursiveAction(partition.get(0), url, username, password);
            invokeAll(db1, db2);
        }
    }

    private void executeBatch(List<String> sqls) {
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            connection.setAutoCommit(false);
            Statement statement = connection.createStatement();
            for (String sql : sqls) {
                statement.addBatch(sql);
            }
            statement.executeBatch();
            statement.clearBatch();
            statement.close();
            connection.commit();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将一组数据平均分成n组
     *
     * @param source 要分组的数据源
     * @param n      平均分成n组
     * @param <T>    泛型
     * @return 拆分后的集合
     */
    public <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<>();
        //(先计算出余数)
        int remainder = source.size() % n;
        //然后是商
        int number = source.size() / n;
        //偏移量
        int offset = 0;
        for (int i = 0; i < n; i++) {
            List<T> value;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }

}
